package com.quanyan.club.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.db.TbClubMsgConsumerRecord;
import com.quanyan.club.entity.db.TbClubOnlineMemberAccount;
import com.quanyan.club.entity.db.TbClubOnlineMemberAccountStream;
import com.quanyan.club.entity.db.TbClubOnlineMemberAccountStreamExample;
import com.quanyan.club.mapper.ClubAccountExtendMapper;
import com.quanyan.club.mapper.TbClubMsgConsumerRecordMapper;
import com.quanyan.club.mapper.TbClubOnlineMemberAccountStreamMapper;
import com.quanyan.club.mq.ClubMedalMsg;
import com.quanyan.club.mq.producer.impl.ClubMedalProducerImpl;
import com.quanyan.club.service.ClubCallBackService;
import com.quanyan.club.service.ClubFinanceMgmService;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.enums.SysCategoryEnum;
import com.quanyan.common.enums.SysClubMedalConditionEnum;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.mq.client.response.MqResponse;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang on 16/8/5.
 */
@Service("clubCallBackService")
public class ClubCallBackServiceImpl implements ClubCallBackService {

    private final static Logger logger = LoggerFactory.getLogger(ClubCallBackServiceImpl.class);

    @Autowired
    private ClubFinanceMgmService clubFinanceMgmService;
    @Autowired
    private ClubAccountExtendMapper clubAccountExtendMapper;
    @Autowired
    private TbClubOnlineMemberAccountStreamMapper clubOnlineMemberAccountStreamMapper;
    @Autowired
    private ClubMedalProducerImpl clubMedalProducerImpl;

    /**
     * 俱乐部成员充值成功回调
     * @param orderNotifyMsg
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public APIResponse rechargePaySuccess(OrderNotifyMsg orderNotifyMsg) {
        //TODO 缺乏信息验证
        //查看该信息是否为充值信息
        int uid = orderNotifyMsg.getUid().intValue();
        int clubId = Integer.parseInt(orderNotifyMsg.getExtraParam());
        String outTradeNo = orderNotifyMsg.getOutTradeNo();

        List<TbClubOnlineMemberAccountStream> streamList = this.clubFinanceMgmService.getClubOnlineMemberAccountStreamByOutTradeNo(
                clubId,
                uid,
                outTradeNo,
                (byte) 2);
        if (!streamList.isEmpty()) {

            TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = streamList.get(0);
            //俱乐部成员账户余额增加
            TbClubOnlineMemberAccount clubOnlineMemberAccount = this.clubFinanceMgmService.getClubOnlineMemberAccount(clubId, uid);
            if (clubOnlineMemberAccount != null) {
                BigDecimal preAmount = clubOnlineMemberAccount.getMoneyTotal();
                BigDecimal money = orderNotifyMsg.getOrderAmount();
                BigDecimal sufAmount = money.add(preAmount);

                clubOnlineMemberAccountStream.setPreAmount(preAmount);
                clubOnlineMemberAccountStream.setSufAmount(sufAmount);
                //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
                clubOnlineMemberAccountStream.setStatus((byte)1);

                Map map = new HashMap<>();
                map.put("money",money);
                map.put("uid",uid);
                map.put("clubId",clubId);
                int n = this.clubAccountExtendMapper.updateClubOnlineMemberAccount(map);

                if(n>0){
                    TbClubOnlineMemberAccountStreamExample example = new TbClubOnlineMemberAccountStreamExample();
                    TbClubOnlineMemberAccountStreamExample.Criteria criteria = example.createCriteria();
                    criteria.andIdEqualTo(clubOnlineMemberAccountStream.getId());
                    //查询条件：订单在处理中的订单
                    criteria.andStatusEqualTo((byte)2);

                    int m = this.clubOnlineMemberAccountStreamMapper.updateByExampleSelective(clubOnlineMemberAccountStream,example);
                    return APIResponse.returnSuccess();
                }

            }else{
                return APIResponse.returnFail("俱乐部成员账户不存在");
            }


        }
        return APIResponse.returnFail("充值记录不存在");
    }

    /**
     * 俱乐部成员充值关闭
     * @param orderNotifyMsg
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public APIResponse rechargePayClose(OrderNotifyMsg orderNotifyMsg) {

        //TODO 缺乏信息验证
        //查看该信息是否为充值信息
        int uid = orderNotifyMsg.getUid().intValue();
        int clubId = Integer.parseInt(orderNotifyMsg.getExtraParam());
        String outTradeNo = orderNotifyMsg.getOutTradeNo();

        List<TbClubOnlineMemberAccountStream> streamList = this.clubFinanceMgmService.getClubOnlineMemberAccountStreamByOutTradeNo(
                clubId,
                uid,
                outTradeNo,
                (byte) 2);
        if (!streamList.isEmpty()) {

            TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = streamList.get(0);
            //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
            clubOnlineMemberAccountStream.setStatus((byte)3);

            TbClubOnlineMemberAccountStreamExample example = new TbClubOnlineMemberAccountStreamExample();
            TbClubOnlineMemberAccountStreamExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(clubOnlineMemberAccountStream.getId());
            //查询条件：订单在处理中的订单
            criteria.andStatusEqualTo((byte)2);

            this.clubOnlineMemberAccountStreamMapper.updateByExampleSelective(clubOnlineMemberAccountStream,example);
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("充值记录不存在");
    }

    /**
     * 俱乐部分享回调
     * @param uid
     * @param clubId
     * @param clubType
     * @return
     */
    @Override
    public MqResponse share(Integer uid, Integer clubId, Integer clubType) {
        Integer categoryId = clubType;
        Integer clubMedalId = 0;
        if (categoryId.equals(SysCategoryEnum.FOOTBALL.getId())) {
            clubMedalId = SysClubMedalConditionEnum.FOOTBALL_SHARE.getId();
        }else if(categoryId.equals(SysCategoryEnum.BASKETBALL.getId())){
            clubMedalId = SysClubMedalConditionEnum.BASKETBALL_SHARE.getId();
        }else if (categoryId.equals(SysCategoryEnum.TENNIS.getId())){
            clubMedalId = SysClubMedalConditionEnum.TENNIS_SHARE.getId();
        }else if (categoryId.equals(SysCategoryEnum.BADMINTON.getId())){
            clubMedalId = SysClubMedalConditionEnum.BADMINTON_SHARE.getId();
        }else if (categoryId.equals(SysCategoryEnum.RUN.getId())){
            clubMedalId = SysClubMedalConditionEnum.RUN_SHARE.getId();
        }else if (categoryId.equals(SysCategoryEnum.CYCLING.getId())){
            clubMedalId = SysClubMedalConditionEnum.CYCLING_SHARE.getId();
        }else if (categoryId.equals(SysCategoryEnum.OUTDOORS.getId())){
            clubMedalId = SysClubMedalConditionEnum.OUTDOORS_SHARE.getId();
        }

        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setMsgId(String.valueOf(System.currentTimeMillis()));
        mqRequestMsg.setTag(MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS);
        mqRequestMsg.setTopic(MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC);

        ClubMedalMsg clubMedalMsg = new ClubMedalMsg();
        clubMedalMsg.setClubId(clubId);
        clubMedalMsg.setCategoryId(categoryId);
        clubMedalMsg.setMedalId(clubMedalId);
        logger.info("俱乐部分享回调发送的mq消息：{}", GsonUtils.toJson(clubMedalMsg));
        mqRequestMsg.setBody(ObjectUtil.toByteArray(clubMedalMsg));
        MqResponse mqResponse = this.clubMedalProducerImpl.syncSend(mqRequestMsg);
        return mqResponse;
    }

    /**
     * 在线充值异常退款回调
     * @param refundNotifyMsg
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public APIResponse rechargeApplyRefundCallBack(RefundNotifyMsg refundNotifyMsg) {
        //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
        //查看该信息是否为充值信息
        int uid = refundNotifyMsg.getUid().intValue();
        String outTradeNo = refundNotifyMsg.getOutTradeNo();
        List<TbClubOnlineMemberAccountStream> streamList = this.clubFinanceMgmService.getClubOnlineMemberAccountStreamByOutTradeNo(
                0,
                uid,
                outTradeNo,
                (byte) 3);
        if (!streamList.isEmpty()) {
            TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = streamList.get(0);
            //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
            clubOnlineMemberAccountStream.setStatus((byte)4);

            TbClubOnlineMemberAccountStreamExample example = new TbClubOnlineMemberAccountStreamExample();
            TbClubOnlineMemberAccountStreamExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(clubOnlineMemberAccountStream.getId());
            //查询条件：订单在处理中的订单
            criteria.andStatusEqualTo((byte)3);

            this.clubOnlineMemberAccountStreamMapper.updateByExampleSelective(clubOnlineMemberAccountStream,example);
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        } else {
            return APIResponse.returnSuccess(ApiResponseEnum.FAIL);
        }
    }

    /**
     * 在线充值异常退款成功回调
     * @param refundNotifyMsg
     * @return
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public APIResponse rechargeRefundCallBack(RefundNotifyMsg refundNotifyMsg) {
        //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
        //查看该信息是否为充值信息
        int uid = refundNotifyMsg.getUid().intValue();
        String outTradeNo = refundNotifyMsg.getOutTradeNo();
        List<TbClubOnlineMemberAccountStream> streamList = this.clubFinanceMgmService.getClubOnlineMemberAccountStreamByOutTradeNo(
                0,
                uid,
                outTradeNo,
                (byte) 4);
        if (!streamList.isEmpty()) {
            TbClubOnlineMemberAccountStream clubOnlineMemberAccountStream = streamList.get(0);
            //0:创建订单 1：已付款 2：待付款 3：已关闭 4：退款中 5：已退款
            clubOnlineMemberAccountStream.setStatus((byte)5);

            TbClubOnlineMemberAccountStreamExample example = new TbClubOnlineMemberAccountStreamExample();
            TbClubOnlineMemberAccountStreamExample.Criteria criteria = example.createCriteria();
            criteria.andIdEqualTo(clubOnlineMemberAccountStream.getId());
            //查询条件：订单在处理中的订单
            criteria.andStatusEqualTo((byte)4);

            this.clubOnlineMemberAccountStreamMapper.updateByExampleSelective(clubOnlineMemberAccountStream,example);
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        } else {
            return APIResponse.returnSuccess(ApiResponseEnum.FAIL);
        }
    }
}
